package com.nunbey.lingxi.lincat.activityinit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;

import java.util.ArrayList;

/**
 * 活动集合：存储所有创建了的集合
 */
public class ActivityCollector {
    /**
     * 单例实例
     */
    private static ActivityCollector activityCollector;
    /**
     * 活动集合
     */
    private final ArrayList<Activity> activityCollection = new ArrayList<>();


    /**
     * 单例线程安全的获取实例
     * @return
     */
    public static synchronized ActivityCollector getActivityCollector(){
        if(activityCollector == null){
            activityCollector = new ActivityCollector();
        }
        return activityCollector;
    }

    /**
     * 增加一个活动
     * @param activity
     */
    synchronized void addActivity(Activity activity){
        activityCollection.add(activity);
    }

    /**
     * 移除一个活动
     * @param activity
     */
    synchronized void removeActivity(Activity activity){
        activityCollection.remove(activity);
    }

    /**
     * 关闭自身进程，这里注意移除活动中没有finish，
     * 而关闭进程中也没有finish，需要直接调用BaseActivity的finish，两者耦合度很大
     */
    @SuppressLint("LongLogTag")
    public synchronized void killProcess(){
        for(int i=0;i<activityCollection.size();i++){
            Activity temp = activityCollection.get(i);
            activityCollection.remove(temp);
            if(!temp.isFinishing()){
                temp.finish();
            }
        }
        Log.d("LinCat/ActivityCollector","killProcess");
        android.os.Process.killProcess(android.os.Process.myPid());
    }

}
